//
//  DataBaseManager.m
//  18-通讯录sqlite
//
//  Created by dllo on 16/8/8.
//  Copyright © 2016年 LST. All rights reserved.
//

#import "DataBaseManager.h"

@implementation DataBaseManager
+ (DataBaseManager *)shareManager {
    static DataBaseManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DataBaseManager alloc] init];
    });
    return manager;
}
- (BOOL)openSQLite3 {
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document = [pathArray firstObject];
    NSString *dbPath = [document stringByAppendingPathComponent:@"people.db"];
    NSLog(@"%@", dbPath);
    int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
    return [self isOperationRusult:result alertText:@"打开数据库"];
    
}
- (BOOL)closeSQLite3 {
    int result = sqlite3_close(dbPoint);
    return [self isOperationRusult:result alertText:@"关闭数据库"];
}
- (BOOL)creatTable {
    [self openSQLite3];
    NSString *createSQL = @"CREATE TABLE people(stu_name TEXT INT PRIMARY KEY)";
    int result = sqlite3_exec(dbPoint, [createSQL UTF8String], NULL , NULL, NULL);
    return [self isOperationRusult:result alertText:@"创建表"];
}
- (BOOL)insertPeople:(AddModel *)people {
    NSString *sqlString = [NSString stringWithFormat:@"insert into people(stu_name) values('%@')", people.name];
    int result = sqlite3_exec(dbPoint, sqlString.UTF8String, NULL , NULL, NULL);
    return [self isOperationRusult:result alertText:@"插入表"];
}
- (NSArray *)selectAllPeople {
    [self openSQLite3];
    NSString *sqlString = @"select * from people";
    sqlite3_stmt *stmt = NULL;
    int result = sqlite3_prepare(dbPoint, sqlString.UTF8String, -1, &stmt, NULL);
    NSMutableArray *array = [NSMutableArray array];
    if (result == SQLITE_OK) {
            while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char * stu_name = sqlite3_column_text(stmt, 0);
            NSString *name = [NSString stringWithUTF8String:(const char *)stu_name];
           AddModel  *peo = [AddModel studentWithName:name];
            [array addObject:peo];
        }
    }
    // 销毁伴随指针
    sqlite3_finalize(stmt);
  [self closeSQLite3];
    return array;
}
- (BOOL)isOperationRusult:(int)result alertText:(NSString *)text {
    BOOL isOperation = YES;
    if (result == SQLITE_OK) {
        NSLog(@"%@成功", text);
        isOperation = YES;
    }else{
        NSLog(@"%@失败%d", text, result);
        isOperation = NO;
    }
    return isOperation;
}

@end
